<template>
  <view class="address-edit-container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <uni-icons type="left" size="24" color="#333"></uni-icons>
      </view>
      <text class="title">{{isEdit ? '编辑地址' : '新增地址'}}</text>
    </view>
    
    <!-- 表单 -->
    <view class="form-container">
      <view class="form-item">
        <text class="label">收货人</text>
        <input type="text" v-model="addressForm.name" placeholder="请输入收货人姓名" />
      </view>
      
      <view class="form-item">
        <text class="label">手机号码</text>
        <input type="number" v-model="addressForm.phone" placeholder="请输入手机号码" maxlength="11" />
      </view>
      
      <view class="form-item">
        <text class="label">所在城市</text>
        <input type="text" v-model="addressForm.city" placeholder="请输入所在城市" />
      </view>
      
      <view class="form-item">
        <text class="label">小区/大厦/学校</text>
        <input type="text" v-model="addressForm.department" placeholder="请输入小区/大厦/学校" />
      </view>
      
      <view class="form-item">
        <text class="label">详细地址</text>
        <input type="text" v-model="addressForm.houseNumber" placeholder="请输入详细地址，如门牌号等" />
      </view>
      
      <view class="form-item switch-item">
        <text class="label">设为默认地址</text>
        <switch :checked="addressForm.isDefault" @change="switchChange" color="#0086ff" />
      </view>
    </view>
    
    <!-- 底部保存按钮 -->
    <view class="save-btn" @click="saveAddress">
      <text>保存</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      addressId: '',
      isEdit: false,
      addressForm: {
        name: '',
        phone: '',
        city: '',
        department: '',
        houseNumber: '',
        isDefault: false
      }
    }
  },
  onLoad(options) {
    if (options.id) {
      this.addressId = options.id;
      this.isEdit = true;
      this.loadAddressDetail();
    }
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    
    loadAddressDetail() {
      // 从服务器获取地址详情
      uni.request({
        url: `http://localhost:3000/address`,
        success: (res) => {
          if (res.statusCode === 200) {
            const addressList = res.data;
            const address = addressList.find(item => item._id === this.addressId);
            
            if (address) {
              this.addressForm = {
                name: address.name,
                phone: address.phone,
                city: address.city,
                department: address.department,
                houseNumber: address.houseNumber,
                isDefault: address.isDefault || false
              };
              // 保存原始ID和其他需要的字段
              this.originalId = address.id;
            }
          }
        },
        fail: (err) => {
          console.error('获取地址详情失败:', err);
          uni.showToast({
            title: '获取地址详情失败',
            icon: 'none'
          });
        }
      });
    },
    
    switchChange(e) {
      this.addressForm.isDefault = e.detail.value;
    },
    
    saveAddress() {
      // 表单验证
      if (!this.addressForm.name) {
        uni.showToast({
          title: '请输入收货人姓名',
          icon: 'none'
        });
        return;
      }
      
      if (!this.addressForm.phone) {
        uni.showToast({
          title: '请输入手机号码',
          icon: 'none'
        });
        return;
      }
      
      if (!/^1\d{10}$/.test(this.addressForm.phone)) {
        uni.showToast({
          title: '手机号码格式不正确',
          icon: 'none'
        });
        return;
      }
      
      if (!this.addressForm.city) {
        uni.showToast({
          title: '请输入所在城市',
          icon: 'none'
        });
        return;
      }
      
      if (!this.addressForm.department) {
        uni.showToast({
          title: '请输入小区/大厦/学校',
          icon: 'none'
        });
        return;
      }
      
      if (!this.addressForm.houseNumber) {
        uni.showToast({
          title: '请输入详细地址',
          icon: 'none'
        });
        return;
      }
      
      // 显示加载中
      uni.showLoading({
        title: '保存中...',
        mask: true
      });
      
      // 准备要保存的地址数据
      const addressData = {
        name: this.addressForm.name,
        phone: this.addressForm.phone,
        city: this.addressForm.city,
        department: this.addressForm.department,
        houseNumber: this.addressForm.houseNumber,
        isDefault: this.addressForm.isDefault,
        // 添加地址完整信息用于显示
        address: `${this.addressForm.city} ${this.addressForm.department} ${this.addressForm.houseNumber}`
      };
      
      // 如果是编辑现有地址
      if (this.isEdit) {
        // 添加必要的ID字段
        addressData._id = this.addressId;
        addressData.id = this.originalId;
        
        // 使用PUT请求更新地址（完全替换）
        uni.request({
          url: `http://localhost:3000/address/${this.originalId}`,
          method: 'PUT',
          data: addressData,
          success: (res) => {
            if (res.statusCode === 200) {
              // 如果当前地址设为默认，需要更新其他地址
              if (addressData.isDefault) {
                this.updateOtherAddressesDefaultStatus();
              } else {
                uni.hideLoading();
                uni.showToast({
                  title: '保存成功',
                  icon: 'success',
                  success: () => {
                    setTimeout(() => {
                      uni.navigateBack();
                    }, 1500);
                  }
                });
              }
            } else {
              uni.hideLoading();
              uni.showToast({
                title: '保存失败',
                icon: 'none'
              });
            }
          },
          fail: (err) => {
            uni.hideLoading();
            console.error('更新地址失败:', err);
            uni.showToast({
              title: '保存失败',
              icon: 'none'
            });
          }
        });
      } else {
        // 新增地址
        // 生成唯一ID
        const uniqueId = Math.random().toString(36).substr(2, 4);
        addressData.id = uniqueId;
        addressData._id = 'address_' + Date.now();
        
        // 发送POST请求添加新地址
        uni.request({
          url: 'http://localhost:3000/address',
          method: 'POST',
          data: addressData,
          success: (res) => {
            if (res.statusCode === 201) {
              // 如果当前地址设为默认，需要更新其他地址
              if (addressData.isDefault) {
                this.updateOtherAddressesDefaultStatus();
              } else {
                uni.hideLoading();
                uni.showToast({
                  title: '添加成功',
                  icon: 'success',
                  success: () => {
                    setTimeout(() => {
                      uni.navigateBack();
                    }, 1500);
                  }
                });
              }
            } else {
              uni.hideLoading();
              uni.showToast({
                title: '添加失败',
                icon: 'none'
              });
            }
          },
          fail: (err) => {
            uni.hideLoading();
            console.error('添加地址失败:', err);
            uni.showToast({
              title: '添加失败',
              icon: 'none'
            });
          }
        });
      }
    },
    
    // 更新其他地址的默认状态
    updateOtherAddressesDefaultStatus() {
      uni.request({
        url: 'http://localhost:3000/address',
        success: (res) => {
          if (res.statusCode === 200) {
            const addressList = res.data;
            
            // 遍历所有地址，将非当前地址的默认状态设为false
            addressList.forEach(address => {
              if (address.id !== this.originalId && address.isDefault) {
                uni.request({
                  url: `http://localhost:3000/address/${address.id}`,
                  method: 'PATCH',
                  data: { isDefault: false },
                  fail: (err) => {
                    console.error('更新其他地址默认状态失败:', err);
                  }
                });
              }
            });
            
            uni.hideLoading();
            uni.showToast({
              title: '保存成功',
              icon: 'success',
              success: () => {
                setTimeout(() => {
                  uni.navigateBack();
                }, 1500);
              }
            });
          }
        },
        fail: (err) => {
          uni.hideLoading();
          console.error('获取地址列表失败:', err);
          uni.showToast({
            title: '保存失败',
            icon: 'none'
          });
        }
      });
    }
  }
}
</script>

<style lang="scss">
.address-edit-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.header {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: #fff;
  
  .back-btn {
    margin-right: 20rpx;
  }
  
  .title {
    flex: 1;
    text-align: center;
    font-size: 32rpx;
    font-weight: bold;
  }
}

.form-container {
  background-color: #fff;
  margin-top: 20rpx;
  
  .form-item {
    display: flex;
    padding: 30rpx 20rpx;
    border-bottom: 1rpx solid #f5f5f5;
    
    .label {
      width: 200rpx;
      font-size: 28rpx;
      color: #333;
    }
    
    input {
      flex: 1;
      font-size: 28rpx;
    }
    
    &.switch-item {
      justify-content: space-between;
    }
  }
}

.save-btn {
  position: fixed;
  bottom: 30rpx;
  left: 30rpx;
  right: 30rpx;
  background-color: #0086ff;
  color: #fff;
  text-align: center;
  padding: 20rpx 0;
  border-radius: 40rpx;
  font-size: 30rpx;
}
</style>